import CURDHelper from '@/utils/CURDHelper'
import PageConfig from '@/utils/pageConfig'
import { getBtnCtr } from '@/utils/BtnControl'
import Query from '@/components/Query';
import { isNumber } from '@/utils/validate';
import { VxeUI } from 'vxe-pc-ui';
import XEUtils from 'xe-utils';
import XLSX from 'xlsx';
export default {
  name: 'ProjectInfo',
  components: {
    Query
  },
  data() {
    const gltxItemRender = {
      name: 'VxeSelect',
      props:{
        filterable: true,
        multiple: true,
        'multi-char-overflow':-1
      },
      options: [],
      events:{ 
        change:e =>{
          this.GetLcmbByTxid()
        }
      }
    }
    const lcmbItemRender = {
      name: 'VxeSelect',
      props:{
        filterable: true,
      },
      options: [],
      
    }
    const khItemRender = {
      name: 'VxeSelect',
      props:{
        filterable: true,
      },
      options: [] 
    }    
    const qdItemRender = {
      name: 'VxeSelect',
      props:{
        filterable: true,
        clearable: true,
      },
      options: [] 
    } 
    return {
      gltxItemRender,
      khItemRender,
      lcmbItemRender,
      qdItemRender,
      componentSize: PageConfig.ComponentSize,
      duration: PageConfig.Duration,
      btnPromission: '',
      editModal: false,
      QueryConditions: [],
      BaseApiUrl: '/api/Xmglxmxx',
      editRow: undefined,
      QueryConfig: [{
        title: '客户名称',
        field: 'khmc',
        type: 'input',
        value: '',
        placeholder: '请输入客户名称以查询',
      },{
        title: '审核状态',
        field: 'shzt',
        type: 'select',
        value: '',
        placeholder: '请输入选择审核状态以查询',
        options: [
          { label: '未审核', value: 'N' },
          { label: '已审核', value: 'Y' }
        ]
      },{
        title: '项目状态',
        field: 'xmzt',
        type: 'select',
        value: 'N',
        placeholder: '请输入选择审核状态以查询',
        options: [
          { label: '未完结', value: 'N' },
          { label: '已完结', value: 'Y' }
        ]
      },{
        title: '体系名称',
        field: 'txid',
        type: 'checkbox',
        value: '',
        chkoptions:[],
        placeholder: '请输入体系名称以查询',
      },{
        title: '合同号',
        field: 'erpbh',
        type: 'input',
        value: '',
        placeholder: '请输入合同号以查询',
      },],
      GridOptions: {
        id:'ProjectInfo_MainGrid',
        border: true,
        stripe: true,
        loading: false,
        size: PageConfig.ComponentSize,
        height: 700,
        columnConfig: {
          resizable: true
        },
        rowConfig: {
          isHover: true,
          isCurrent:true
        },
        checkboxConfig: {
          highlight: true,
          range: true
        },
        exportConfig: {
        },
        toolbarConfig: {
          custom: true,
          export: true,
          slots: {
            buttons: 'customButtons'
          }
        },        
        customConfig:{
          mode:'drawer',
          storage:true
        },
        columns: [
          { type: 'seq', width: 50 },
          { type: 'checkbox', width: 35 },
          { field: 'txid', title: '体系ID', visible: false  },
          { field: 'erpbh', title: '合同号', minWidth: 100, showOverflow: true },
          { field: 'khmc', title: '客户名称', minWidth: 120, showOverflow: true },
          { field: 'qdmc', title: '渠道名称', minWidth: 120, showOverflow: true },
          { field: 'txmc', title: '体系名称', minWidth: 120, showOverflow: true },
          { field: 'txgg', title: '体系规格',  minWidth: 100, showOverflow: true },
          { field: 'rzbz', title: '体系版本', minWidth: 120, showOverflow: true },          
          { field: 'lcmbmc', title: '项目流程', minWidth: 80, showOverflow: true },
          { field: 'lxr', title: '联系人', minWidth: 100, showOverflow: true },
          { field: 'lxdh', title: '联系人手机', minWidth: 100, showOverflow: true },
          { field: 'lxyx', title: '联系人邮箱', minWidth: 120, showOverflow: true },
          { field: 'sfdcs', title: '是否多场所', minWidth: 120, showOverflow: true },
          { field: 'dcslb', title: '多场所类别', minWidth: 120, showOverflow: true },
          { field: 'shzt', title: '审核状态',  minWidth: 80, showOverflow: true ,slots:{ default:'auditStatus'}},
          { field: 'shr', title: '审核人', minWidth: 80, showOverflow: true },
          { field: 'shsj', title: '审核时间',  minWidth: 120, showOverflow: true},   
          // { field: 'zslb', title: '证书类别', minWidth: 120, showOverflow: true },
          // { field: 'zsh', title: '证书号', minWidth: 120, showOverflow: true },
          { field: 'zydm', title: '专业代码', minWidth: 120, showOverflow: true },
          { field: 'rzfw', title: '认证范围',  minWidth: 100, showOverflow: true },
          { field: 'txrs', title: '体系人数',  minWidth: 80, showOverflow: true },
          // { field: 'zsksrq', title: '证书开始日期',  minWidth: 120, showOverflow: true ,
          //   formatter: ({cellValue}) => XEUtils.toDateString(cellValue,'yyyy-MM-dd')
          // },
          // { field: 'zsjsrq', title: '证书结束日期',  minWidth: 120, showOverflow: true ,
          //   formatter: ({cellValue}) => XEUtils.toDateString(cellValue,'yyyy-MM-dd')
          // },
          { field: 'sf', title: '省份',  minWidth: 120, showOverflow: true },
          { field: 'sxq', title: '区域',  minWidth: 120, showOverflow: true },
          { field: 'htlx', title: '合同类型',  minWidth: 120, showOverflow: true },
          { field: 'htdz', title: '合同地址',  minWidth: 120, showOverflow: true },
          { field: 'shlx', title: '审核类型',  minWidth: 100, showOverflow: true },
          { field: 'csje', title: '初审金额',  minWidth: 80, showOverflow: true },
          { field: 'jsje', title: '监审金额',  minWidth: 80, showOverflow: true },
          { field: 'htje', title: '合同金额',  minWidth: 80, showOverflow: true },
          { field: 'htqdrq', title: '合同签订日期',  minWidth: 120, showOverflow: true,
            formatter: ({cellValue}) => XEUtils.toDateString(cellValue,'yyyy-MM-dd')
          },                
          { field: 'createtime', title: '创建时间', width: 120, showOverflow: true },
          { field: 'createname', title: '创建人', width: 60, showOverflow: true },
          { field: 'updatetime', title: '更新时间', width: 120, showOverflow: true },
          { field: 'updatename', title: '更新人', width: 60, showOverflow: true },
          { field: 'operation', title: '操作', fixed: 'right', width: 160, slots: { default: 'operation' } },
        ],
        data: []
      },
      PagerConfig: {
        align: 'center',
        pageSize: 25,
        total: 0,
        currentPage: 1,
        pageSizes: [10, 25, 50, 100, 200],
      },
      FormOptions: {
        'title-width': 100,
        border: true,
        titleBackground: true,
        data: {
          id: -1,
          lcmb:undefined,
          createid: '',
          createtime: '',
          createname: '',
          updateid: '',
          updatetime: '',
          updatename: '',
          khid: undefined,
          txid: undefined,
          erpbh: '',
          sf:'',
          sxq: '',
          shlx: '',
          rzfw: '',
          txrs: '',
          csje: undefined,
          jsje: undefined,
          htqdrq: undefined,
          bz: '',
          htje:undefined,
          sfdcs:undefined,
          dcslb:undefined,
          htlx:undefined,
          htdz:undefined,
          qdid:undefined,
          txids:''
        },
        rules: {
          txid: [{ required: true, message: '请选择体系名称', trigger: 'blur' }],
          lcmb: [{ required: true, message: '请选择流程模板', trigger: 'blur' }],
          erpbh: [{ required: true, message: '请填写合同号', trigger: 'blur' }],
          khid: [{ required: true, message: '请选择客户信息', trigger: 'blur' }],
          shlx: [{ required: true, message: '请选择审核类型', trigger: 'blur' }],
          rzfw: [{ required: true, message: '请选择认证范围', trigger: 'blur' }],
          txrs: [{ required: true, message: '请输入体系人数', trigger: 'blur' ,validator: this.ValidatorNumber}],
          csje: [{ required: true, message: '请输入初审金额', trigger: 'blur' ,validator: this.ValidatorNumber}],
          htje: [{ required: true, message: '请输入合同金额', trigger: 'blur' ,validator: this.ValidatorNumber}],
          jsje: [{ required: true, message: '请输入监审金额', trigger: 'blur' ,validator: this.ValidatorNumber}],
          htqdrq: [{ required: true, message: '请选择合同日期', trigger: 'blur' }],
        },
        items: [
          { field: 'txid', title: '体系名称', span: 12, itemRender: gltxItemRender, placeholder: '请选择体系名称' },
          { field: 'lcmb', title: '流程模板', span: 12, itemRender: lcmbItemRender, placeholder: '请选择流程模板' },
          { field: 'khid', title: '客户名称', span: 12, itemRender: khItemRender, placeholder: '请选择客户名称' },
          { field: 'erpbh', title: '合同号', span: 12, itemRender:{name:'VxeInput'}, placeholder: '请输入合同号' },
          { field: 'htlx', title: '合同类型', span: 12, itemRender: { name: 'VxeSelect', 
            options: [{ label: '初审', value: '初审' }, { label: '监一', value: '监一' },
              { label: '监二', value: '监二'},{ label: '再认证', value: '再认证'}] }, placeholder: '请选择合同类型' },
          { field: 'sf', title: '省份', span: 12, itemRender:{name:'VxeInput'}, placeholder: '请输入省份' },
          { field: 'sxq', title: '区域', span: 12, itemRender:{name:'VxeInput'}, placeholder: '请输入区域' },
          { field: 'shlx', title: '审核类型', span: 12, itemRender: { name: 'VxeSelect', 
            options: [{ label: '初认证', value: '初认证' }, { label: '监一', value: '监一' },
              { label: '监二', value: '监二'},{ label: '再认证', value: '再认证'},
              { label: '扩大', value: '扩大'},{ label: '补充', value: '补充'},,{ label: '不符合现场验证', value: '不符合现场验证'}] }, placeholder: '请选择审核类型' },
          { field: 'txrs', title: '体系人数', span: 12, placeholder: '请输入体系人数', 
            itemRender: { name: 'VxeInput', clearable: true, placeholder: '请输入体系人数' } },
          { field: 'qdid', title: '渠道名称', span: 12, itemRender: qdItemRender },
          { field: 'rzfw', title: '认证范围', span: 24, itemRender: {  name: 'VxeTextarea', maxlegnth: 500, clearable: true, 
            showWordCount: true }},
          { field: 'csje', title: '初审金额', span: 12, placeholder: '请输入初审金额',
            itemRender: { name: 'VxeInput',  clearable: true, placeholder: '请输入初审金额' ,
              events:{ change:e =>{this.FormOptions.data.htje = this.FormOptions.data.csje}}} },
          { field: 'jsje', title: '监审金额', span: 12, placeholder: '请输入监审金额',
            itemRender: { name: 'VxeInput',  clearable: true, placeholder: '请输入监审金额' } },
          { field: 'htje', title: '合同金额', span: 12, placeholder: '请输入合同金额',
              itemRender: { name: 'VxeInput',  clearable: true, placeholder: '请输入合同金额' } }, 
          { field: 'htqdrq', title: '合同日期', span: 12, itemRender: { name: 'VxeDatePicker', type: 'date', valueFormat: 'YYYY-MM-DD', 
            placeholder: '请选择签单日期' } },
          { field: 'sfdcs', title: '是否多场所', span: 12, itemRender: { name: 'VxeSelect', 
            options: [{ label: '', value: '' },{ label: '是', value: '是' }, { label: '否', value: '否' }] }, placeholder: '请选择是否多场所'},
          { field: 'dcslb', title: '多场所类别', span: 12, itemRender: { name: 'VxeSelect', 
             options: [{ label: '', value: '' },{ label: '延伸', value: '延伸' }, { label: '支持', value: '支持' }
              , { label: '支持、延伸', value: '支持、延伸' }, { label: '集团', value: '集团' }
             ],clearable: true }, placeholder: '请选择多场所类别'},
          { field: 'zydm', title: '专业代码', span: 24, itemRender: { name: 'VxeInput', clearable: true, placeholder: '请输入专业代码'}}, 
          { field: 'htdz', title: '合同地址', span: 24, itemRender: { name: 'VxeInput', clearable: true, placeholder: '请输入合同地址'}}, 
          { field: 'bz', title: '备注', span: 24, itemRender: { name: 'VxeTextarea', maxlegnth: 500, clearable: true, showWordCount: true }, 
            placeholder: '请输入备注' },
          {
            align: 'center',
            span: 24,
            // itemRender: {
            //   name: 'VxeButtonGroup',
            //   options: [{
            //     type: 'submit', content: '提交', status: 'primary'
            //   }, {
            //     type: 'reset', content: '重置'
            //   }]
            // }
            slots:{default:'action'}
          }
        ]
      },
      importModal:false,
      ImportGridOptions: {
        id:'ProjectInfo_ImportGrid',
        border: true,
        stripe: true,
        loading: false,
        size: PageConfig.ComponentSize,
        height: 550,
        columnConfig: {
          resizable: true
        },
        rowConfig: {
          isHover: true,
          isCurrent:true
        },
        checkboxConfig: {
          highlight: true,
          range: true
        },
        columns: [
          { type: 'seq', width: 50 },
          { type: 'checkbox', width: 35 },
          { field: 'erpbh', title: '合同号', minWidth: 100, showOverflow: true },
          { field: 'khmc', title: '客户名称', minWidth: 120, showOverflow: true },
          { field: 'lxr', title: '联系人', minWidth: 100, showOverflow: true },
          { field: 'lxdh', title: '联系人手机', minWidth: 100, showOverflow: true },
          { field: 'lxyx', title: '联系人邮箱', minWidth: 120, showOverflow: true },
          { field: 'sfdcs', title: '是否多场所', minWidth: 120, showOverflow: true },
          { field: 'dcslb', title: '多场所类别', minWidth: 120, showOverflow: true },
          { field: 'zslb', title: '证书类别', minWidth: 120, showOverflow: true },
          { field: 'zsh', title: '证书号', minWidth: 120, showOverflow: true },
          { field: 'zydm', title: '专业代码', minWidth: 120, showOverflow: true },
          { field: 'rzfw', title: '认证范围',  minWidth: 100, showOverflow: true },
          { field: 'txmc', title: '体系名称', minWidth: 120, showOverflow: true },
          { field: 'txgg', title: '体系规格',  minWidth: 100, showOverflow: true },
          { field: 'rzbz', title: '体系版本', minWidth: 120, showOverflow: true },
          { field: 'txrs', title: '体系人数',  minWidth: 80, showOverflow: true },
          { field: 'zsksrq', title: '证书开始日期',  minWidth: 80, showOverflow: true },
          { field: 'zsjsrq', title: '证书结束日期',  minWidth: 80, showOverflow: true },
          { field: 'sf', title: '省份',  minWidth: 120, showOverflow: true },
          { field: 'sxq', title: '区域',  minWidth: 120, showOverflow: true },
          { field: 'htlx', title: '合同类型',  minWidth: 120, showOverflow: true },
          { field: 'htdz', title: '合同地址',  minWidth: 120, showOverflow: true },
          { field: 'shlx', title: '审核类型',  minWidth: 100, showOverflow: true },
          { field: 'csje', title: '初审金额',  minWidth: 80, showOverflow: true },
          { field: 'jsje', title: '监审金额',  minWidth: 80, showOverflow: true },
          { field: 'htje', title: '合同金额',  minWidth: 80, showOverflow: true },
          { field: 'htqdrq', title: '合同签订日期',  minWidth: 80, showOverflow: true },
          { field: 'mcshrq', title: '初审末次时间',  minWidth: 80, showOverflow: true },
          { field: 'xctxsj', title: '下次提醒',  minWidth: 80, showOverflow: true },
          { field: 'zszt', title: '证书状态',  minWidth: 80, showOverflow: true },
        ],
        data: []
      },
      ImportTx:[]
    }
  },
  created() {
    // 动态头部按钮
    this.btnPromission = getBtnCtr(
      this.$route.path,
      this.$store.getters.userPermission
    )
    this.GetTxOptions();
    this.GetKhOptions();
    this.GetQdOptions();
  },
  methods: {
    ValidatorNumber(e) {
      if (!isNumber(e.itemValue)) {
        return new Error('请输入数字');
      } else {
        if (e.itemValue < 0) {
          return new Error('请输入大于等于0的数字');
        }
      }
    },
    handleQuery(e) {
      this.QueryConditions = e;
      this.DoQuery(e);
    },
    handlePageChange() {
      this.DoQuery(this.QueryConditions);
    },
    handleBatchDelete() {
      let rows = this.$refs.maingrid.getCheckboxRecords(true);
      this.DoBatchDelete(rows);
    },
    handleAdd() {
      this.FormOptions.data = {
        id: -1,
        lcmb:undefined,
        createid: '',
        createtime: '',
        createname: '',
        updateid: '',
        updatetime: '',
        updatename: '',
        khid: undefined,
        txid: undefined,
        erpbh: '',
        sxq: '',
        sf:'',
        shlx: '',
        rzfw: '',
        txrs: '',
        csje: undefined,
        jsje: undefined,
        htqdrq: undefined,
        bz: '',
        htje:0,        
        sfdcs:undefined,
        dcslb:undefined,        
        htlx:undefined,
        htdz:undefined,
        qdid:undefined,
        txids:''
      };
      this.editModal = true;      
    },
    handleEdit(row) {
      this.editRow = row;
      this.FormOptions.data = row;
      if(row.txids && row.txids.length > 0){      
        this.FormOptions.data.txid = row.txids.split(',').map(p => +p);
      }
      this.GetLcmbByTxid();
      this.editModal = true;
    },
    handleDelete(row) {
      if(row.shzt == 'Y') {
        VxeUI.modal.message({content: '已审核的数据不能删除',status: 'error',duration: this.duration})
        return; 
      }
      this.DoDelete(row);
    },
    handleEditModalSubmit() {
      if(this.FormOptions.data.shzt == 'Y') {
       VxeUI.modal.confirm({
          id:'ConfirmEdit',
          title:'确认框',
          content:'该数据已审核，是否编辑合同号和渠道信息?'
        }).then(e => {
          if(e == 'cancel'){
            this.editModal = false;
          }else{
            this.DoEdit();
          }
        }).catch(e => {
          return;
        })
      }else{
        this.FormOptions.data.id == -1 ? this.DoAdd() : this.DoEdit();
      }
      
    },
    handleEditModalReset() {

    },
    handleAudit(row) {
      this.DoAudit(row);
    },
    handleBatchAudit() {
      let rows = this.$refs.maingrid.getCheckboxRecords(true);
      this.DoBatchAudit(rows);
    },
    handleImport(){
      this.DoImport();      
    },
    handleImprotConfirm(){
      this.DoImportConfirm();
    },
    DoQuery(e) {
      let request = {
        isPaging: true,
        pageSize: this.PagerConfig.pageSize,
        pageIndex: this.PagerConfig.currentPage,
        queryConditions: e,
        orderByConditions: [{
          column:'t.id',
          condition:'desc'
        }]
      }
      CURDHelper.Query(request, this.BaseApiUrl)
        .then(res => {
          this.GridOptions.data = res.data;
          this.PagerConfig.total = res.totalNumber;
        }).catch(err => {
          VxeUI.modal.message({content: `${err}`,status: 'error',duration: this.duration})
        })
    },
    DoAdd() {
      if(this.FormOptions.data.txid.length > 1){
        this.FormOptions.data.txids = this.FormOptions.data.txid.join(',')
        this.FormOptions.data.txid = this.FormOptions.data.txid[0];        
      }else if(this.FormOptions.data.txid.length == 1){
        this.FormOptions.data.txid = this.FormOptions.data.txid[0];
        this.FormOptions.data.txids = '';
      }
      //新增
      CURDHelper.Add(this.FormOptions.data, null, this.BaseApiUrl)
        .then(res => {
          VxeUI.modal.message({content: '新增数据成功',status: 'success',duration: this.duration})
          this.$refs.editForm.reset();
          this.FormOptions.data.id = -1;
          this.editModal = false;
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          if(err.indexOf('ERPBH_SHLX') > -1){
            VxeUI.modal.message({ content: `当前合同号和审核类型的项目信息已存在`, status: 'error', duration: this.duration })
          }else{
            VxeUI.modal.message({ content: `${err}`, status: 'error', duration: this.duration })
          }
          
        })
    },
    DoEdit() {
      //编辑
      if(this.FormOptions.data.txid.length > 1){
        this.FormOptions.data.txids = this.FormOptions.data.txid.join(',')
        this.FormOptions.data.txid = this.FormOptions.data.txid[0];        
      }else if(this.FormOptions.data.txid.length == 1){
        this.FormOptions.data.txid = this.FormOptions.data.txid[0];
        this.FormOptions.data.txids = '';
      }
      CURDHelper.Edit(this.FormOptions.data, null, this.BaseApiUrl)
        .then(res => {
          VxeUI.modal.message({ content: '编辑数据成功',status: 'success',duration: this.duration})          
          this.editModal = false;
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          VxeUI.modal.message({content: `${err}`,status: 'error',duration: this.duration})
        })
    },
    DoDelete(row) {
      //删除
      let deleteModel = {
        ID: row.id,
        DeleteRemark: ''
      };
      CURDHelper.DeleteWithConfirm('是否删除当前数据', deleteModel, null, this.BaseApiUrl)
        .then(res => {
          VxeUI.modal.message({content: '删除数据成功',status: 'success',duration: this.duration})
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          VxeUI.modal.message({content: `${err}`,status: 'error',duration: this.duration})
        })
    },
    DoBatchDelete(rows) {
      //删除
      let deleteList = [];
      rows.forEach(row => {
        if(row.shzt != 'Y'){
        deleteList.push({ID: row.id,DeleteRemark: ''})
        }
      });
      if(deleteList.length == 0){
        VxeUI.modal.message({content: '没有需要删除的数据，或者已审核不能进行删除操作',status:'error',duration: this.duration});
        return;
      }
      CURDHelper.DeleteWithConfirm('是否删除当前已选择数据，删除后不能恢复', null, deleteList, this.BaseApiUrl)
        .then(res => {
          VxeUI.modal.message({content: '删除数据成功',status: 'success',duration: this.duration})
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          VxeUI.modal.message({content: `${err}`,status: 'error',duration: this.duration})
        })
    },
    DoAudit(row){
      if(row.shzt == 'Y'){
       //数据审核
      let postData = {
        ID: row.id,
        shzt: 'N'
      }
      CURDHelper.EditWithConfirm('是否反审核当前项目信息？', postData, null, `${this.BaseApiUrl}/Audit`)
        .then(res => {
          VxeUI.modal.message({ content: '反审核数据成功',status: 'success',duration: this.duration});          
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          VxeUI.modal.message({content: `${err}`,status: 'error',duration: this.duration})
        })
      }else{
      let postData = {
        ID: row.id,
        shzt: 'Y'
      }
      CURDHelper.EditWithConfirm('是否审核当前项目信息？', postData, null, `${this.BaseApiUrl}/Audit`)
        .then(res => {
          VxeUI.modal.message({ content: '审核数据成功',status: 'success',duration: this.duration});          
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          VxeUI.modal.message({content: `${err}`,status: 'error',duration: this.duration})
        })
      }
      
    },
    DoBatchAudit(row){
      let postList = [];
      row.forEach(row => {
        if(row.shzt != 'Y'){         
          postList.push({ID: row.id,shzt: 'Y'})
        }
      });
      if(postList.length == 0){
        VxeUI.modal.message({content: '当前已审核数据无需重复审核',status:'error',duration: this.duration});
        return;
      }
      CURDHelper.EditWithConfirm('是否审核当前项目信息，审核后不允许反审', null, postList, `${this.BaseApiUrl}/Audit`)
        .then(res => {
          VxeUI.modal.message({ content: '审核数据成功',status: 'success',duration: this.duration});          
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          VxeUI.modal.message({content: `${err}`,status: 'error',duration: this.duration})
        })
    },
    DoImport(){
      VxeUI.readFile().then((e) => {
        const reader = new FileReader()
        this.ImportGridOptions.data = [];
        reader.onload = e => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const resultJosn = XLSX.utils.sheet_to_json(worksheet, { raw: false, dateNF: 'yyyy-MM-dd', cellDates: true });
          resultJosn.forEach(item => {
            if(!item['合同号'] || !item['公司名称'] || !item['体系'] || !item['体系版本'] 
              ||!item['认证范围'] || (item['初审/复评费'] && item['初审/复评费'].length < 0) 
              ||(item['监督审核费'] && item['监督审核费'].length < 0) ||!item['合同签订日期'] 
              ||!item['初审末次时间'] ||!item['提醒时间']){
              console.log(item)
              return;
            }
           console.log(item)
            var currZsksrq = item['证书开始时间'];           
            var currZsjsrq = item['证书结束时间'];                
            var currHtqdrq = item['合同签订日期'];                 
            var currMcshsj = item['初审末次时间'];                 
            var currXctxsj = item['提醒时间'];     
           
            let newRow = {
              erpbh: item['合同号'],
              khmc: item['公司名称'],
              lxr: item['联系人'],
              lxdh: item['联系人手机'],
              lxyx: item['联系人邮箱'],
              sfdcs: item['是否多场所'],
              dcslb: item['多场所类别'],
              zslb: item['证书类别'],
              zsh: item['证书号'],
              zydm: item['专业代码'],
              rzfw: item['认证范围'],
              txmc: item['体系'],
              txgg: item['体系版本'],
              rzbz: item['体系版本'],
              txrs: item['体系人数'],
              zsksrq: currZsksrq,
              zsjsrq: currZsjsrq, 
              sxq: item['区域'],
              sf:item['省份'],
              htlx: item['合同类型'],
              htdz: item['合同地址'],
              shlx: item['审核类型'],
              csje: item['初审/复评费'],
              jsje: item['监督审核费'],
              htje: item['初审/复评费'],
              htqdrq: currHtqdrq,
              mcshrq: currMcshsj,
              shzt:item['审核状态'],
              xctxsj:currXctxsj,
              zszt:item['证书状态'] == '未完成' ? '有效' : item['证书状态'],
              qdmc:item['渠道名称']
            }
            this.ImportGridOptions.data.push(newRow);
          })
          this.importModal = true;
        }
        reader.readAsArrayBuffer(e.file);
      })
    },
    DoImportConfirm(){
      let postList = this.$refs.importModalGrid.getCheckboxRecords(true) ;
      if(!postList || postList.length < 1){
        postList = this.ImportGridOptions.data;
      }
      CURDHelper.Add(null,postList, this.BaseApiUrl)
        .then(res => {
          VxeUI.modal.message({content: '导入数据成功',status: 'success',duration: this.duration});          
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          VxeUI.modal.message({ content: `${err}`, status: 'error', duration: this.duration })
        })
    },
    GetTxOptions() {
      let request = {
        isPaging: false,
        pageSize: 1,
        pageIndex: 1,
        queryConditions: [],
        orderByConditions: []
      }
      CURDHelper.Query(request, '/api/Xmjcgltx')
        .then(res => {
          this.gltxItemRender.options = [];
          res.data.forEach(item => {
            this.gltxItemRender.options.push({
              value: item.id,
              label: item.txmc
            })
            this.QueryConfig[3].chkoptions.push({
              label:item.id,
              value:item.id,
              content:item.txmc
            })
          })
        }).catch(err => {
          VxeUI.modal.message({content: `${err}`,status: 'error',duration: this.duration})
        })
    },
    GetKhOptions() {
      let request = {
        isPaging: false,
        pageSize: 1,
        pageIndex: 1,
        queryConditions: [],
        orderByConditions: []
      }
      CURDHelper.Query(request, '/api/Xmjckhxx')
        .then(res => {
          this.khItemRender.options = [];
          res.data.forEach(item => {
            this.khItemRender.options.push({
              value: item.id,
              label: item.khmc
            })
          })
        }).catch(err => {
          VxeUI.modal.message({content: `${err}`,status: 'error',duration: this.duration})
        })
    },
    GetQdOptions() {
      let request = {
        isPaging: false,
        pageSize: 1,
        pageIndex: 1,
        queryConditions: [],
        orderByConditions: []
      }
      CURDHelper.Query(request, '/api/Xmjcqdxx')
        .then(res => {
          this.qdItemRender.options = [];
          res.data.forEach(item => {
            this.qdItemRender.options.push({
              value: item.id,
              label: item.qdmc
            })
          })
        }).catch(err => {
          VxeUI.modal.message({content: `${err}`,status: 'error',duration: this.duration})
        })
    },
    GetLcmbByTxid() {
      if(!this.FormOptions.data.txid || this.FormOptions.data.txid.length < 1){
        this.FormOptions.data.lcmb = undefined;
        this.lcmbItemRender.options = [];
        return;
      }
      let txid = this.FormOptions.data.txid;
      if(this.FormOptions.data.txid.length > 0){
        txid = this.FormOptions.data.txid[0];
      } 
      let request = {
        isPaging: false,
        pageSize: 1,
        pageIndex: 1,
        queryConditions: [{
          column:'gltxid',
          condition:6,
          content: txid
        }],
        orderByConditions: []
      }
      CURDHelper.Query(request, '/api/xmjclcxxzb')
        .then(res => {
          this.lcmbItemRender.options = [];
          res.data.forEach(item => {
            this.lcmbItemRender.options.push({
              value: item.id,
              label: item.lcmbmc
            })
          })

        }).catch(err => {
          VxeUI.modal.message({content: `${err}`,status: 'error',duration: this.duration})
        })
    },
    handleImportProjectInfo(){
      this.DoImportProjectInfo();
    },
    DoImportProjectInfo(){
      VxeUI.readFile().then((e) => {
        const reader = new FileReader()       
        reader.onload = e => {
          
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const resultJosn = XLSX.utils.sheet_to_json(worksheet);
         
          if(resultJosn.length <= 0){
            return;
          }
          var item = resultJosn[0];
          let khid = this.GetKhid(item['企业名称']);
          if(khid == -1){
            VxeUI.modal.message({content: `信息导入失败，请添加该客户基础信息后导入!`,status: 'error',duration: this.duration});
            return;
          }
          this.GetTx(item['体系人数']);
          this.GetShlx(item['体系/审核类型']);
          this.GetRzfw(item['认证范围']);

          if(this.ImportTx.length < 1){
            VxeUI.modal.message({content: `信息导入失败，没有体系人数信息!`,status: 'error',duration: this.duration});
            return;
          }

          let txid = this.GetTxid(this.ImportTx[0].txmc)
          if(txid == -1){
            VxeUI.modal.message({content: `信息导入失败，请添加管理体系后导入!`,status: 'error',duration: this.duration});
            return;
          }
          this.FormOptions.data.khid = khid;
          this.FormOptions.data.txid = txid;
          this.GetLcmbByTxid(txid);
          if(this.ImportTx[0].shlx.indexOf('初') > -1){
            this.FormOptions.data.shlx = '初认证';
            this.FormOptions.data.htlx = '初审';
          }else if(this.ImportTx[0].shlx.indexOf('再') > -1){
            this.FormOptions.data.shlx = '再认证';
            this.FormOptions.data.htlx = '再认证';
          }else if(this.ImportTx[0].shlx.indexOf('监一') > -1){
            this.FormOptions.data.shlx = '监一';
            this.FormOptions.data.htlx = '监一';
          }else if(this.ImportTx[0].shlx.indexOf('监二') > -1){
            this.FormOptions.data.shlx = '监二';
            this.FormOptions.data.htlx = '监二';
          }
          this.FormOptions.data.txrs = this.ImportTx[0].txrs;
          this.FormOptions.data.rzfw = this.ImportTx[0].rzfw;
          this.FormOptions.data.sf = item['市县区'].substring(0,item['市县区'].indexOf('省')+1);
          this.FormOptions.data.sxq = item['市县区'].substring(item['市县区'].indexOf('省')+1);
          this.FormOptions.data.csje = item['合同初审金额'];
          this.FormOptions.data.jsje = item['合同监督金额'];
          this.FormOptions.data.htje = item['合同初审金额'];   
          let date2 = new Date('1900-01-01');
          let currHtrq = date2.setDate(item['合同签订日期']);
          this.FormOptions.data.htqdrq = XEUtils.toDateString(currHtrq,'yyyy-MM-dd')        
          this.FormOptions.data.erpbh = item['合同号'];
          console.log(this.FormOptions.data)
        }
        reader.readAsArrayBuffer(e.file);
      })
    },
    GetKhid(khmc){
      for(let i = 0;i<this.khItemRender.options.length;i++){
        let item = this.khItemRender.options[i];
        if(item.label == khmc){
          return item.value;
        }
      }
      return -1;
    },
    GetTxid(txmc){
      for(let i = 0;i<this.gltxItemRender.options.length;i++){
        let item = this.gltxItemRender.options[i];
        if(item.label == txmc){
          return item.value;
        }
      }
      return -1;
    },
    GetTx(txmc){
      this.ImportTx = [];
      if(txmc.indexOf('\n') > -1){
        let txlist = txmc.split('\n');
        txlist.forEach(tx =>{
          let currTxmc = tx.split(':');
          this.ImportTx.push({
            txmc:currTxmc[0].trim(),
            txrs:currTxmc[1].trim(),
            shlx:undefined,
            rzfw:undefined
          });
        })
      }else{
         let currTxmc = txmc.split(':');
         this.ImportTx.push({
          txmc:currTxmc[0].trim(),
          txrs:currTxmc[1].trim(),
          shlx:undefined,
          rzfw:undefined
         })
      }
    },
    GetShlx(shlx){
      if(this.ImportTx.length < 1){
        return;
      }
      if(this.ImportTx.length > 1){
        let currShlxList = shlx.split('\n');
        for(let i=0;i<this.ImportTx.length;i++){
          this.ImportTx[i].shlx = currShlxList[i].split(':')[1].trim();
        }
      }else{
        this.ImportTx[0].shlx = shlx.split(':')[1].trim();
      }
    },
    GetRzfw(rzfw){
      if(this.ImportTx.length < 1){
        return;
      }
      if(this.ImportTx.length > 1){
        let currRzfwList = rzfw.split('\n');
        for(let i=0;i<this.ImportTx.length;i++){
          this.ImportTx[i].rzfw = currRzfwList[i].split(':')[1].trim();
        }
      }else{
        this.ImportTx[0].rzfw = rzfw.split(':')[1].trim();
      }
    }
  }
}
